package com.ccnf.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ccnf.core.utils.ResultUtil;
import com.ccnf.model.entity.Exhibitor;
import com.ccnf.model.entity.SocialUser;
import com.ccnf.model.mapper.ExhibitorMapper;
import com.ccnf.model.mapper.SocialUserMapper;
import com.ccnf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangxieliu
 * @since 2018-04-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<SocialUserMapper, SocialUser> implements UserService {
    @Autowired
    private ExhibitorMapper exhibitorMapper;

    @Override
    public SocialUser saveUser(SocialUser socialUser) {
        SocialUser selectSocialUser = baseMapper.selectByOpenId(socialUser.getOpenId());// 通过用户的openId查询用户信息
        if (selectSocialUser == null) {
            ResultUtil.validateSQL(baseMapper.insert(socialUser), "用户信息录入失败");
            return socialUser;
        } else {
            // 设置无需更新的字段值
            socialUser.setUnionId(null);// 会管家用户ID
            socialUser.setOpenId(null);// 微信openId
            socialUser.setChatId(null);// 用户聊天ID
            // 设置需要更新的用户ID
            socialUser.setUserId(selectSocialUser.getUserId());// 用户ID
            ResultUtil.validateSQL(baseMapper.updateById(socialUser), "更新用户信息失败");
        }
        return selectSocialUser;
    }

    @Override
    public SocialUser findByUnionId(String unionId) {
        return baseMapper.selectByUnionId(unionId);
    }

    @Override
    public void saveExhibitor(Exhibitor exhibitor) {
        if (exhibitorMapper.selectById(exhibitor.getUserId()) == null) {
            ResultUtil.validateSQL(exhibitorMapper.insert(exhibitor), "认证失败");
        }
    }

    @Override
    public void modifyExhibitor(Exhibitor exhibitor) {
        Exhibitor selectExhibitor = new Exhibitor();
        selectExhibitor.setPhone(exhibitor.getPhone());
        selectExhibitor.setExpoId(exhibitor.getExpoId());
        ResultUtil.validateSQL(exhibitorMapper.update(exhibitor, new EntityWrapper<>(selectExhibitor)), "展商信息更新失败");
    }

    @Override
    public Exhibitor findExhibitorByUserId(Long expoId, Long userId) {
        Exhibitor exhibitor = new Exhibitor();
        exhibitor.setUserId(userId);
        if (expoId == null) {
            expoId = 0L;
        }
        exhibitor.setExpoId(expoId);
        return exhibitorMapper.selectOne(exhibitor);
    }

    @Override
    public Page<Map<String, Object>> findExhibitors(Long expoId, Page page) {
        return page.setRecords(exhibitorMapper.selectAll(expoId, page));
    }
}